<script lang="js" setup>
import { ref } from "vue";
import {getRouteParams, goNeighborhood} from "../../tools/go";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import {
  addComment,
  addLikeComment,
  addLikePost, deleteLikeComment,
  deleteLikePost_1,
  getPostById
} from "../../api/neighborhood/neighborhood";
import {baseUrl} from "../../api/http";
import {getUserId} from "../../store";


const isFollowed = ref(false);
const isLiked = ref(false);
const isCollected = ref(false);
const commentCount = ref(36);
const commentText = ref("");
const isInputFocused = ref(false);

const hidden = ref(false)

//评论表单
let formData = new FormData()

//图片预览
const previewImg = ref("");

//回复阶层
const step = ref(0)

const comments = ref([
  {
    avatar:
        "../../src/static/logo.png",
    nickname: "老弟漫步者",
    content: "真的很美！",
    img: "src/static/logo.png",
    time: "10分钟前",
    likes: 12,
    isLiked: false,
  },
  {
    avatar:
        "../../src/static/logo.png",
    nickname: "花间小筑",
    content: "老弟拍得真好，请问是用什么相机拍的呀？",
    time: "25分钟前",
    likes: 8,
    isLiked: false,
  },
]);

// 关注作者
const handleFollow = () => {
  isFollowed.value = !isFollowed.value;
  uni.showToast({
    title: isFollowed.value ? "已关注" : "已取消关注",
    icon: "none",
  });
};

// 点赞帖子
const handleLike = () => {
  if (!isLiked.value) {
    addLikePost({
      sourceId: postInfo.value.id,
      founder: getUserId(),
      status: 0
    }).then(res => {
      if (res.code === 200) {
        isLiked.value = true
        postInfo.value.likeNum++
      }
    })
  } else {
    deleteLikePost_1(
        postInfo.value.id,
        getUserId()
    ).then(res => {
      if (res.code === 200) {
        isLiked.value = false
        postInfo.value.likeNum--
      }
    })
  }
};

// 收藏帖子
const handleCollect = () => {
  isCollected.value = !isCollected.value;
  uni.showToast({
    title: isCollected.value ? "已收藏" : "已取消收藏",
    icon: "none",
  });
};

// 分享
const handleShare = () => {
  uni.showToast({
    title: "作者不允许该帖子分享。敬请期待",
    icon: "none",
  });
};

// 显示更多操作
const showMoreActions = () => {
  uni.showActionSheet({
    itemList: ["举报", "不感兴趣"],
    success: (res) => {
      if (res.tapIndex === 0) {
        uni.showToast({ title: "举报成功", icon: "none" });
      }
    },
  });
};

// 焦点输入框
const focusComment = () => {
  isInputFocused.value = true;
};

//点赞评论
const likeComment = (index) => {

  if (!index.userId.includes(getUserId())) {
    addLikeComment({
      founder: 23,
      status: 0,
      commentId: index.id,
      type: 1
    }).then(res => {
      init()
    })
  } else {
    deleteLikeComment(index.id, getUserId()).then(res => {
      init()
    })
  }



};

//回复评论
const replyComment = (comment) => {
  commentText.value = `回复 @${comment.nickName}: `;
  formData.delete("step")
  formData.append("step", comment.id)
  step.value = comment.id
  isInputFocused.value = true;
};

// 帖子信息
const postInfo = ref({
  avatar: "",
  commentNum: 0,
  content: "",
  file: [],
  id:23,
  likeNum: 1,
  likesId: [23],
  nickName: "bbm",
  time:"2025-02-26 03:08:51",
  type:"分享生活",
  comments:[]
})


//选择图片
const uploadImage = () => {
  let input = document.createElement("input");
  input.type = "file";
  input.accept = "image/*";
  input.onchange = (e) => {
    let file = e.target.files[0];
    let reader = new FileReader();

    reader.onload = (e) => {
      previewImg.value = e.target.result;
    };

    reader.readAsDataURL(file);
    formData.delete("img")
    formData.append("img", file)
  }
  input.click()
};

//删除图片
const deleteImage = () => {
  previewImg.value = "";
  formData.delete("img")
  formData.append("img", "")
};

//预览图片
const previewImage = (url) => {
  uni.previewImage({
    current: 0,
    urls: [url],
  });
};

// 发送评论
const sendComment = () => {
  if (commentText.value.trim()) {


    formData.append("content", commentText.value)
    formData.append("postId", postInfo.value.id)
    formData.append("userId", getUserId())
    formData.append("step",0)

    if (formData.get("img") === null) {
      formData.delete("img")
      formData.append("img", new Blob([]))
    }

    addComment(formData).then(res => {
      init()
      commentText.value = "";
      previewImg.value = "";
      isInputFocused.value = false;
      step.value = 0
      formData.delete("step")
      formData.delete("content")
      formData.delete("postId")
      formData.delete("userId")
    })


  }
};

//回复评论的发送评论按钮
const sendReplyComment = () => {
  if (commentText.value.trim()) {

    formData.append("content", commentText.value)
    formData.append("postId", postInfo.value.id)
    formData.append("userId", getUserId())

    if (formData.get("img") === null) {
      formData.delete("img")
      formData.append("img", new Blob([]))
    }

    addComment(formData).then(res => {
      init()
      commentText.value = "";
      previewImg.value = "";
      isInputFocused.value = false;
      step.value = 0
      formData.delete("step")
      formData.delete("content")
      formData.delete("postId")
      formData.delete("userId")
    })
  }
}

const noReply = () => {
  step.value = 0
  commentText.value = "";
}

const PostById = () => {
  getPostById(getRouteParams("id")).then(res => {
      postInfo.value = res.data

      for (let i = 0; i < res.data.likesId.length; i++) {
        if (res.data.likesId[i] === getUserId()) {
          isLiked.value = true
          break
        }
      }

  })
}



const init = () => {
  PostById()
}
init()

</script>


<template>
  <view class="back">
    <view class="post-detail">
      <!-- 顶部导航栏 -->
      <view class="nav-bar">
        <uni-icons class="back-icon" type="back" @click="goNeighborhood" size="24"  />
        <text class="nav-title"></text>
        <view class="nav-right">
          <uni-icons
              class="share-icon"
              type="redo"
              size="24"
              @click="handleShare"
          />
          <uni-icons
              class="more-icon"
              type="more-filled"
              size="24"
              @click="showMoreActions"
          />
        </view>
      </view>

      <!-- 内容区域 -->
      <scroll-view class="content-scroll" scroll-y>
        <!-- 作者信息 -->
        <view class="author-info">
          <image class="avatar" :src="baseUrl + postInfo.avatar" mode="aspectFill" />
          <view class="author-detail">
            <text class="nickname">{{postInfo.nickName}}</text>
            <text class="post-time">{{ postInfo.time }}</text>
          </view>
          <button class="follow-btn" size="mini" @click="handleFollow">
            {{ isFollowed ? '已关注' : '关注' }}
          </button>
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
          <text class="post-title">{{postInfo.content.substring(0,7)}}</text>
          <text class="post-text">{{postInfo.content}}</text>
          <view class="image-grid">
              <view v-for="(file, index) in postInfo.file">
                <image
                    v-if="file.type !== 'm4v'"
                    :src="baseUrl + file.clientUrl"
                    mode="aspectFill"
                    class="post-image"
                    @click="previewImage(index)"
                />
                <video
                    v-else
                    :src="baseUrl + file.clientUrl"
                    object-fit="cover"
                />
              </view>
          </view>
          <view class="tags">
            <text class="tag">#樱花季</text>
            <text class="tag">#mc</text>
            <uni-icons class="location" type="location" size="24"></uni-icons>
            <text class="location">mc公园</text>
          </view>
        </view>

        <!-- 互动功能区 -->
        <view class="interaction-bar">
          <view class="interaction-item" @click="handleLike">
            <uni-icons
                :type="isLiked ? 'heart-filled' : 'heart'"
                size="24"
                :color="isLiked ? '#ff6b6b' : '#666'"
            />
            <text>{{ postInfo.likeNum }}</text>
          </view>
          <view class="interaction-item" @click="focusComment">
            <uni-icons type="chat" size="24" />
            <text>{{ postInfo.commentNum }}</text>
          </view>
          <view class="interaction-item" @click="handleCollect">
            <uni-icons
                :type="isCollected ? 'star-filled' : 'star'"
                size="24"
                :color="isCollected ? '#ffd43b' : '#666'"
            />
            <text>收藏</text>
          </view>
          <view class="interaction-item" @click="handleShare">
            <uni-icons type="redo" size="24" />
            <text>分享</text>
          </view>
        </view>

        <!--遮罩层-->
        <view class="hhh" v-if="step !== 0" @click="noReply"></view>

        <!-- 评论区 -->
        <view class="comment-section">
          <view class="comment-header">
            <text class="comment-title">评论 {{ postInfo.commentNum }}</text>
          </view>
          <view class="comment-list">
            <view
                v-for="(comment, index) in postInfo.comments"
                :key="index"
            >
              <view class="comment-item">
                <image
                    class="comment-avatar"
                    :src="baseUrl + comment.avatar"
                    mode="aspectFill"
                />
                <view class="comment-content">
                  <text class="comment-nickname">{{ comment.nickName }}</text>
                  <text class="comment-text">{{ comment.content }}</text>

                  <image @click="previewImage(baseUrl + comment.fileClient)" style="width: 200px;height: 110px" v-if="comment.fileClient" :src="baseUrl + comment.fileClient" />

                  <view class="comment-footer">
                    <text class="comment-time">{{ comment.time }}</text>
                    <view class="comment-actions">
                      <view class="like-btn" @click="likeComment(comment)">
                        <uni-icons
                            :type="comment.userId.includes(getUserId()) ? 'heart-filled' : 'heart'"
                            size="14"
                            :color="comment.userId.includes(getUserId()) ? '#ff6b6b' : '#666'"
                        />
                        <text>{{ comment.commentLike }}</text>
                      </view>
                      <text class="reply-btn" @click="replyComment(comment)">回复</text>
                    </view>
                  </view>
                </view>
              </view>

              <view class="reply_comment" v-if="hidden === comment.id && comment.childComment.length !== 0">
                <view class="comment-item" v-for="(c) in comment.childComment">
                  <image
                      class="comment-avatar"
                      :src="baseUrl + c.avatar"
                      mode="aspectFill"
                  />
                  <view class="comment-content">
                    <text class="comment-nickname">{{ c.nickName }}</text>
                    <text class="comment-text">{{ c.content }}</text>

                    <image @click="previewImage(baseUrl + c.fileClient)" style="width: 200px;height: 110px" v-if="c.fileClient" :src="baseUrl + c.fileClient" />

                    <view class="comment-footer">
                      <text class="comment-time">{{ c.time }}</text>
                      <view class="comment-actions">
                        <view class="like-btn" @click="likeComment(c)">
                          <uni-icons
                              :type="c.userId.includes(getUserId()) ? 'heart-filled' : 'heart'"
                              size="14"
                              :color="c.userId.includes(getUserId()) ? '#ff6b6b' : '#666'"
                          />
                          <text>{{ c.commentLike }}</text>
                        </view>
                        <text class="reply-btn" @click="replyComment(c)">回复</text>
                      </view>
                    </view>
                  </view>
                </view>



              </view>

              <view class="hidden" v-if="comment.childComment.length !== 0" @click="hidden = hidden === comment.id ? false: comment.id" >{{ hidden !== comment.id ? `有 ${comment.childComment.length} 条评论 展开` : '收起' }}</view>
            </view>
          </view>
        </view>

      </scroll-view>

      <!-- 底部评论栏 -->
      <view class="bottom" v-if="step === 0">
        <view class="comment-bar">
          <textarea
              class="comment-input"
              type="text"
              placeholder="说点什么..."
              v-model="commentText"
              :focus="isInputFocused"
              :auto-height="true"
              :maxlength="-1"
          />
          <uni-icons
              class="image-btn"
              type="image"
              size="24"
              @click="uploadImage"
          />
          <button
              class="send-btn"
              size="mini"
              :disabled="!commentText.trim()"
              @click="sendComment"
          >
            发送
          </button>
        </view>

        <view class="user_select_img" v-if="previewImg !== ''">

          <v-badge icon="$close" color="red" @click="deleteImage">
            <img style="width: 200px;height: 110px"   :src="previewImg" />
          </v-badge>

        </view>
      </view>


      <!-- 底部评论栏 -->
      <view class="bottom" v-else>
        <view class="comment-bar">
          <textarea
              class="comment-input"
              type="text"
              :placeholder="commentText"
              v-model="commentText"
              :focus="isInputFocused"
              :auto-height="true"
              :maxlength="-1"
          />
          <uni-icons
              class="image-btn"
              type="image"
              size="24"
              @click="uploadImage"
          />
          <button
              class="send-btn"
              size="mini"
              :disabled="!commentText.trim()"
              @click="sendReplyComment"
          >
            回复
          </button>
        </view>

        <view class="user_select_img" v-if="previewImg !== ''">

          <v-badge icon="$close" color="red" @click="deleteImage">
            <img style="width: 200px;height: 110px"   :src="previewImg" />
          </v-badge>

        </view>
      </view>

    </view>
  </view>
</template>


<style lang="scss" scoped>
@use "../../static/css/main";
.back {
  @include main.useTheme() {
    .post-detail {
      .content-scroll {
        .comment-section {
          .comment-header {
            margin-bottom: 30rpx;
          }

          .comment-title {
            font-size: 16px;
            font-weight: 500;
            color: main.getVal("primary_text_color");
          }

          .comment-item {

            .comment-content {

              .comment-footer {
                .comment-time {
                  font-size: 12px;
                  color: #999999;
                }

                .comment-actions {
                  display: flex;
                  align-items: center;
                  gap: 20rpx;
                }

                .like-btn {
                  display: flex;
                  align-items: center;
                  gap: 6rpx;
                }

                .like-btn text {
                  font-size: 12px;
                  color: main.getVal("one_lv_text_color");
                }

                .reply-btn {
                  font-size: 12px;
                  color: #666666;
                }
                display: flex;
                justify-content: space-between;
                align-items: center;
              }

              .comment-nickname {
                font-size: 14px;
                font-weight: 500;
                color: main.getVal("primary_text_color");
                display: block;
                margin-bottom: 10rpx;
              }

              .comment-text {
                font-size: 14px;
                color: main.getVal("one_lv_text_color");
                line-height: 1.5;
                display: block;
                word-wrap: break-word;
                margin-bottom: 10rpx;
                width: 80vw;
              }
              flex: 1;
            }

            .comment-avatar {
              width: 60rpx;
              height: 60rpx;
              border-radius: 30rpx;
              margin-right: 20rpx;
              border: 1px solid main.getVal("primary_border_color");
            }
            display: flex;
            margin-bottom: 30rpx;
          }

          .hidden {
            font-size: 12px;
            color: #666666;
            margin-left: 120rpx;
            margin-bottom: 30rpx;
          }

          .reply_comment {

            .comment-item {

              .comment-content {

                .comment-footer {
                  .comment-time {
                    font-size: 12px;
                    color: #999999;
                  }

                  .comment-actions {
                    display: flex;
                    align-items: center;
                    gap: 20rpx;
                  }

                  .like-btn {
                    display: flex;
                    align-items: center;
                    gap: 6rpx;
                  }

                  .like-btn text {
                    font-size: 12px;
                    color: main.getVal("one_lv_text_color");
                  }

                  .reply-btn {
                    font-size: 12px;
                    color: #666666;
                  }
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                }

                .comment-nickname {
                  font-size: 14px;
                  font-weight: 500;
                  color: main.getVal("primary_text_color");
                  display: block;
                  margin-bottom: 10rpx;
                }

                .comment-text {
                  font-size: 14px;
                  color: main.getVal("one_lv_text_color");
                  line-height: 1.5;
                  display: block;
                  word-wrap: break-word;
                  margin-bottom: 10rpx;
                  width: 60vw;
                }
                flex: 1;
              }

              .comment-avatar {
                width: 60rpx;
                height: 60rpx;
                border-radius: 30rpx;
                margin-right: 20rpx;
                border: 1px solid main.getVal("primary_border_color");
              }
              display: flex;
            }
            margin-left: 60rpx;
            margin-bottom: 30rpx;
          }





          margin-top: 20rpx;
          background-color: main.getVal("primary_bg_color");
          padding: 30rpx 30rpx 100px;
        }

        .interaction-bar {
          .interaction-item {
            display: flex;
            align-items: center;
            gap: 10rpx;
          }

          .interaction-item text {
            font-size: 14px;
            color: main.getVal("one_lv_text_color");
          }
          display: flex;
          justify-content: space-around;
          padding: 20rpx 0;
          background-color: main.getVal("primary_bg_color");
          margin-top: 20rpx;
        }

        .post-content {
          .tags {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 20rpx;
          }

          .tag {
            font-size: 12px;
            color: #5c7cfa;
            background-color: #edf2ff;
            padding: 8rpx 20rpx;
            border-radius: 20rpx;
          }

          .location {
            font-size: 12px;
            color: main.getVal("other_lv_text_color");
          }

          .post-title {
            font-size: 18px;
            font-weight: bold;
            color: main.getVal("primary_text_color");
            display: block;
            margin-bottom: 20rpx;
          }

          .post-text {
            font-size: 14px;
            color: main.getVal("one_lv_text_color");
            line-height: 1.6;
            display: block;
            margin-bottom: 20rpx;
          }

          .image-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10rpx;
            margin-bottom: 20rpx;
          }

          .post-image {
            width: 100%;
            height: 220rpx;
            border-radius: 8rpx;
          }
          padding: 30rpx;
          background-color: main.getVal("primary_bg_color");
          margin-top: 20rpx;
        }

        .author-info {
          .post-time {
            font-size: 12px;
            color: #999999;
            margin-top: 4rpx;
            display: block;
          }

          .follow-btn {
            background-color: #ff6b6b;
            color: #ffffff;
            border-radius: 30rpx;
          }


          .avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 40rpx;
            margin-right: 20rpx;
          }

          .author-detail {
            flex: 1;
          }

          .nickname {
            font-size: 16px;
            font-weight: 500;
            color: main.getVal("primary_text_color");
            display: block;
          }
          display: flex;
          align-items: center;
          padding: 30rpx;
          background-color: main.getVal("primary_bg_color");
        }
        flex: 1;
        overflow: auto;
      }

      .bottom {
        .user_select_img {
          width: 100%;
          padding: 0 30rpx;
        }

        .comment-bar {
          .comment-input {
            flex: 1;
            background-color: main.getVal("primary_bg_color");
            border-radius: 30rpx;
            padding: 10rpx 20rpx;
            margin-right: 20rpx;
            font-size: 15px;
          }

          .image-btn {
            margin-right: 20rpx;
          }

          .send-btn {
            background-color: #ff6b6b;
            color: #ffffff;
            border-radius: 30rpx;
          }

          .send-btn[disabled] {
            background-color: #ced4da;
            color: #ffffff;
          }

          display: flex;
          width: 100%;
          align-items: center;
          padding: 10rpx 30rpx;
          background-color: main.getVal("two_lv_bg_color");
          border-top: 1px solid main.getVal("one_lv_border_color");
          flex-shrink: 0;

        }
        position: fixed;
        bottom: 0;
        width: 100%;
        z-index: 100;
        background: main.getVal("two_lv_bg_color");
      }


      .hhh{
        position: fixed;
        top: 0;
        height: 95%;
        z-index: 1;
        width: 100%;
        background: rgba(0,0,0,0.5);
      }

      .nav-bar {
        .nav-title {
          font-size: 16px;
          font-weight: 500;
          color: main.getVal("one_lv_text_color");
        }

        .nav-right {
          display: flex;
          align-items: center;
          gap: 30rpx;
        }
        height: 88rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;
        background-color: main.getVal("one_lv_bg_color");
        border-bottom: 1px solid main.getVal("primary_border_color");
        flex-shrink: 0;
      }
      height: 100%;
      display: flex;
      flex-direction: column;
      background-color: main.getVal('one_lv_bg_color');
    }
  }
}
</style>
